from django.core.management.base import BaseCommand 
from ability.models import  Image
from tencentcloud.cvm.v20170312 import models
from ability.cloud import client 


class Command(BaseCommand):
    help = 'sync public images from tcent clount'

    def handle(self, *args, **options):
      pagenation = 20
      offset = 0
      while 1:
        req = models.DescribeImagesRequest()
        Filter = models.Filter()
        Filter.Name = 'image-type'
        Filter.Values = ['PRIVATE_IMAGE', 'SHARED_IMAGE']
        req.Filters = [Filter]
        req.Offset = offset
        req.Limit = pagenation
        resp = client.DescribeImages(req)
        #  "ImageId":"img-bd747i3r",
        #     "OsName":"Ubuntu Server 20.04 LTS 64位",
        #     "ImageType":"PRIVATE_IMAGE",
        #     "CreatedTime":"2020-11-22T02:00:05Z",
        #     "ImageName":"Ubuntu20-04-python",
        #     "ImageDescription":"Ubuntu 20.04 64 bit python3",
        #     "ImageSize":50,
        #     "Architecture":"x86_64",
        #     "ImageState":"NORMAL",
        #     "Platform":"Ubuntu",
        #     "ImageCreator":"100009034229",
        #     "ImageSource":"CREATE_IMAGE",
        #     "SyncPercent":null,
        #     "IsSupportCloudinit":true,
        for imageObj in resp.ImageSet:
          image = Image.objects.filter(imageId=imageObj.ImageId).filter(owner=None).first()
          if image is None:
            image_new = Image()
            image_new.image_name = imageObj.ImageName
            image_new.image_type = 1
            image_new.image_url = ''
            image_new.imageId = imageObj.ImageId
            image_new.import_status = 2
            image_new.opration_system = imageObj.OsName
            image_new.platform = imageObj.Platform
            image_new.version = imageObj.OsName
            image_new.architecture = imageObj.Architecture
            image_new.save()
          else:
            image.image_name = imageObj.ImageName
            image.status = 'N'
            image.save()
        if len(resp.ImageSet) < pagenation:
          break
        offset += pagenation
      